package org.example.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.example.common.BodyReaderHttpServletRequestWrapper;
import org.example.common.BusinessException;
import org.example.common.HygResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liyishan
 * @date 2023/4/18 16:14
 */

public class WebKit {
    static Logger logger = LoggerFactory.getLogger(WebKit.class);
    private static String pattern = "^Mozilla/\\d\\.\\d\\s+\\(+.+?\\)";
    private static String pattern2 = "\\(+.+?\\)";
    private static Pattern r;
    private static Pattern r2;
    public static final String HVYOSV_AUTH_HEADER = "Authorization";

    public WebKit() {
    }

    public static void setCORS(HttpServletResponse response, String origin) {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization, Authorization-Worker, Authorization-Cooperator");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Origin", origin);
    }

    public static void loggerSheer(BodyReaderHttpServletRequestWrapper requestWrapper, Logger log) {
        log.info("请求info:ip:{},url:{},\n\tparam:{},\n\tcontent-type:{},\n\torigin:{},\n\treferer:{},\n\tUser-Agent:{}", new Object[]{IpUtil.getRequestIp(requestWrapper), requestWrapper.getRequestURL(), requestWrapper.getBodyS(), requestWrapper.getContentType(), requestWrapper.getHeader("Origin"), requestWrapper.getHeader("Referer"), requestWrapper.getHeader("User-Agent")});
    }

    public static void loggerDefault(BodyReaderHttpServletRequestWrapper requestWrapper, Logger log) {
        log.info("请求info:ip:{},url:{},\n\tparam:{},\n\tcontent-type:{},\n\torigin:{},\n\treferer:{},\n\tUser-Agent:{}", new Object[]{IpUtil.getRealIp(requestWrapper), requestWrapper.getRequestURL(), "敏感信息，不打印参数", requestWrapper.getContentType(), requestWrapper.getHeader("Origin"), requestWrapper.getHeader("Referer"), requestWrapper.getHeader("User-Agent")});
    }

    public static void response(HttpServletResponse response, HygResponse mesResponse) {
        response(response, JSONObject.toJSONString(mesResponse));
    }

    public static void response(HttpServletResponse response, String bodys) {
        PrintWriter writer = null;

        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            writer = response.getWriter();
            writer.write(bodys);
            writer.flush();
            writer.close();
        } catch (IOException var4) {
            logger.error("数据响应异常 IOException:", var4);
        }

    }

    public static String getDeviceInfo(String userAgent) {
        if (!userAgent.contains("CFNetwork") && !userAgent.contains("Darwin")) {
            Matcher m = r.matcher(userAgent);
            String result = null;
            if (m.find()) {
                result = m.group(0);
            }

            if (StringUtils.isEmpty(result)) {
                return userAgent;
            } else {
                Matcher m2 = r2.matcher(result);
                if (m2.find()) {
                    result = m2.group(0);
                }

                result = result.replace("(", "");
                result = result.replace(")", "");
                return filterDeviceInfo(result);
            }
        } else {
            return userAgent;
        }
    }

    private static String filterDeviceInfo(String result) {
        if (StringUtils.isEmpty(result)) {
            return null;
        } else {
            result = result.replace(" U;", "");
            result = result.replace(" zh-cn;", "");
            return result;
        }
    }

    public static Map<String, String> getReqParam(HttpServletRequest request) {
        Map<String, String> params = new HashMap();
        Map requestParams = request.getParameterMap();
        Iterator iter = requestParams.keySet().iterator();

        while(iter.hasNext()) {
            String name = (String)iter.next();
            String[] values = (String[])((String[])requestParams.get(name));
            String valueStr = "";

            for(int i = 0; i < values.length; ++i) {
                valueStr = i == values.length - 1 ? valueStr + values[i] : valueStr + values[i] + ",";
            }

            params.put(name, valueStr);
        }

        return params;
    }

    public static String map2ParamGet(Map<String, String> params) {
        return map2ParamGet(params, true);
    }

    public static String map2ParamGet(Map<String, String> params, boolean isUrlEncoder) {
        boolean first = true;
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for(Iterator var4 = params.entrySet().iterator(); var4.hasNext(); first = false) {
                Map.Entry<String, String> entry = (Map.Entry)var4.next();
                if (first) {
                    sb.append("?");
                } else {
                    sb.append("&");
                }

                sb.append((String)entry.getKey());
                sb.append("=");
                String value = (String)entry.getValue();

                try {
                    if (StringUtils.isEmpty(value)) {
                        if (isUrlEncoder) {
                            sb.append(URLEncoder.encode(value, "UTF-8"));
                        }

                        sb.append(value);
                    }
                } catch (UnsupportedEncodingException var8) {
                    throw new RuntimeException("URLEncoder error  please check it.");
                }
            }
        }

        return sb.toString();
    }

    public static UrlEncodedFormEntity map2PostEntity(Map<String, String> params) {
        List<NameValuePair> nvps = new ArrayList();
        Set<String> keys = params.keySet();
        Iterator var3 = keys.iterator();

        while(var3.hasNext()) {
            String key = (String)var3.next();
            nvps.add(new BasicNameValuePair(key, (String)params.get(key)));
        }

        try {
            return new UrlEncodedFormEntity(nvps, "utf-8");
        } catch (UnsupportedEncodingException var5) {
            throw new RuntimeException("URLEncoder error  please check it.");
        }
    }

    public static StringEntity map2PostJsonEntity(Map<String, String> params) {
        return new StringEntity(JSONObject.toJSONString(params), "utf-8");
    }

    public static StringEntity obj2PostJsonEntity(Object object) {
        return new StringEntity(JSONObject.toJSONString(object), "utf-8");
    }

    public static void write(File file, String charset, HttpServletResponse response) {
        if (file == null) {
            throw new BusinessException("文件为空");
        } else {
            OutputStream os = null;

            try {
                response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
                response.setContentType("application/x-msdownload;charset=" + charset);
                os = response.getOutputStream();
                os.write(FileUtils.copyToByteArray(file));
                os.flush();
            } catch (IOException var8) {
                logger.error("cvs文件流写出失败,错误原因:", var8);
            } finally {
                close((InputStream)null, os);
            }

        }
    }

    public static void close(InputStream inputStream, OutputStream outputStream) {
        try {
            if (null != inputStream) {
                inputStream.close();
            }

            if (null != outputStream) {
                outputStream.close();
            }

        } catch (IOException var3) {
            throw new RuntimeException(var3);
        }
    }

    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new HashMap();
        Enumeration headerNames = request.getHeaderNames();

        while(headerNames.hasMoreElements()) {
            String key = (String)headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }

        return map;
    }

    public static StringEntity map2PostXMLEntity(Map<String, String> params) {
        return new StringEntity(XmlUtils.mapToXml(params), "utf-8");
    }

    static {
        r = Pattern.compile(pattern);
        r2 = Pattern.compile(pattern2);
    }
}
